package com.lekang.service.impl;

import java.util.List;

import com.lekang.common.core.domain.AjaxResult;
import com.lekang.common.utils.DateUtils;
import com.lekang.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lekang.mapper.NursingLevelMapper;
import com.lekang.domain.NursingLevel;
import com.lekang.service.INursingLevelService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 护理等级Service业务层处理
 *
 * @author ruoyi
 * @date 2025-10-14
 */
@Service
public class NursingLevelServiceImpl implements INursingLevelService
{
    @Autowired
    private NursingLevelMapper nursingLevelMapper;

    /**
     * 查询护理等级
     *
     * @param id 护理等级主键
     * @return 护理等级
     */
    @Override
    public NursingLevel selectNursingLevelById(Long id)
    {
        return nursingLevelMapper.selectNursingLevelById(id);
    }

    /**
     * 查询护理等级列表
     *
     * @param nursingLevel 护理等级
     * @return 护理等级
     */
    @Override
    public List<NursingLevel> selectNursingLevelList(NursingLevel nursingLevel)
    {
        List<NursingLevel> list = nursingLevelMapper.selectNursingLevelList(nursingLevel);
        // 为每个护理等级设置是否被老人使用的标识
        for (NursingLevel level : list) {
            int elderlyCount = nursingLevelMapper.countElderlyByLevelId(level.getId());
            level.setIsUsedByElderly(elderlyCount > 0);
        }
        return list;
    }

    /**
     * 新增护理等级
     *
     * @param nursingLevel 护理等级
     * @return 结果
     */
    @Override
    public int insertNursingLevel(NursingLevel nursingLevel)
    {
        // 校验护理等级名称是否重复
        if (StringUtils.isNotEmpty(nursingLevel.getLevelName()))
        {
            NursingLevel existLevel = nursingLevelMapper.selectNursingLevelByName(nursingLevel.getLevelName());
            if (existLevel != null)
            {
                throw new RuntimeException("护理等级名称已存在");
            }
        }
        nursingLevel.setCreateTime(DateUtils.getNowDate());
        return nursingLevelMapper.insertNursingLevel(nursingLevel);
    }

    /**
     * 修改护理等级
     *
     * @param nursingLevel 护理等级
     * @return 结果
     */
    @Override
    public int updateNursingLevel(NursingLevel nursingLevel)
    {
        // 校验：是否被老人使用
        int elderlyCount = nursingLevelMapper.countElderlyByLevelId(nursingLevel.getId());
        if (elderlyCount > 0) {
            throw new RuntimeException("该护理等级已被 " + elderlyCount + " 位老人使用，无法修改");
        }
        
        // 校验护理等级名称是否重复（排除自身）
        if (StringUtils.isNotEmpty(nursingLevel.getLevelName()))
        {
            NursingLevel existLevel = nursingLevelMapper.selectNursingLevelByName(nursingLevel.getLevelName());
            if (existLevel != null && !existLevel.getId().equals(nursingLevel.getId()))
            {
                throw new RuntimeException("护理等级名称已存在");
            }
        }
        return nursingLevelMapper.updateNursingLevel(nursingLevel);
    }

    /**
     * 批量删除护理等级
     *
     * @param ids 需要删除的护理等级主键
     * @return 结果
     */
    @Override
    public int deleteNursingLevelByIds(Long[] ids)
    {
        // 检查每个护理等级是否被使用
        for (Long id : ids) {
            int elderlyCount = nursingLevelMapper.countElderlyByLevelId(id);
            if (elderlyCount > 0) {
                NursingLevel level = nursingLevelMapper.selectNursingLevelById(id);
                String levelName = (level != null) ? level.getLevelName() : "ID=" + id;
                throw new RuntimeException("护理等级【" + levelName + "】已被 " + elderlyCount + " 位老人使用，无法删除");
            }
        }
        return nursingLevelMapper.deleteNursingLevelByIds(ids);
    }

    /**
     * 删除护理等级信息
     *
     * @param id 护理等级主键
     * @return 结果
     */
    @Override
    public int deleteNursingLevelById(Long id)
    {
        // 校验：是否被老人使用
        int elderlyCount = nursingLevelMapper.countElderlyByLevelId(id);
        if (elderlyCount > 0) {
            NursingLevel level = nursingLevelMapper.selectNursingLevelById(id);
            String levelName = (level != null) ? level.getLevelName() : "ID=" + id;
            throw new RuntimeException("护理等级【" + levelName + "】已被 " + elderlyCount + " 位老人使用，无法删除");
        }
        return nursingLevelMapper.deleteNursingLevelById(id);
    }

    @Override
    @Transactional
    public AjaxResult updateLevelWithBinding(NursingLevel level, List<Long> planIds) {
        // 0. 校验：是否被老人使用
        int elderlyCount = nursingLevelMapper.countElderlyByLevelId(level.getId());
        if (elderlyCount > 0) {
            return AjaxResult.error("该护理等级已被 " + elderlyCount + " 位老人使用，无法修改");
        }
        
        // 1. 更新护理等级主表
        int mainResult = nursingLevelMapper.updateNursingLevel(level);
        if (mainResult <= 0) {
            return AjaxResult.error("修改护理等级失败");
        }
        // 2. 删除旧中间表关联
        nursingLevelMapper
                .deleteBindingByLevelId(level.getId());
        // 3. 插入新中间表关联（若有选中的计划）
        if (planIds != null && !planIds.isEmpty()) {
            nursingLevelMapper
                    .batchInsertBinding(level.getId(), planIds);
        }
        return AjaxResult.success("修改成功");
    }
}